package com.szxy.backend.item.service.impl;

import com.szxy.backend.item.service.FileUploadService;
import com.szxy.utils.FtpUtil;
import com.szxy.utils.IDUtils;
import com.szxy.utils.Result;
import org.apache.commons.net.ftp.FTP;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Auther:zwer
 * @Date:2019/9/7 17:29
 * @Description:com.szxy.backend.item.service.impl
 * @Version:1.0
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${FTP_HOST}")
    private String FTP_HOST;
    @Value("${FTP_PROT}")
    private Integer FTP_PROT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;
    @Value("${FTP_BASEPATH}")
    private String FTP_BASEPATH;
    @Value("${FTP_FILEPATH}")
    private String FTP_FILEPATH;
    @Value("${IMG_URL_SUFFIX}")
    private String IMG_URL_SUFFIX;

    @Override
    public Result uploadFile(MultipartFile file) {
        InputStream input = null;
        try {
            //按上传时间创建图片存在目录
            String dateStr = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            String timePath = "/"+dateStr+"/";
            String filePath = FTP_FILEPATH+timePath;
            //修改上传文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String filename = IDUtils.genImageName()+suffix;
            input = file.getInputStream();
            // 上传图片
            boolean flag = FtpUtil.uploadFile(FTP_HOST, FTP_PROT, FTP_USERNAME, FTP_PASSWORD, FTP_BASEPATH, filePath, filename, input);
            if(flag){
                String imgUrl = IMG_URL_SUFFIX+timePath+filename;
                return Result.ok(imgUrl); //返回图片地址
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(input != null){
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
